import 'dart:async';

import 'package:bluetooth_protocols_parser_plugin/library.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/protocol_mixin.dart';
import 'package:inmotion_pro/pages/models/firmware_info_model.dart';
import 'package:inmotion_pro/pages/models/vehicle_model.dart';
import 'package:inmotion_pro/pages/others/common_enum/firmware_update_type.dart';
import 'package:inmotion_pro/service/vehicle_connection_service.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:inmotion_pro/utils/utils.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../../http/api_helper.dart';
import '../../../models/http_response/firmware_info_response_model.dart';
import 'state.dart';

class OtaController extends GetxController with ProtocolMixin {
  final OtaState state = OtaState();

  @override
  void onInit() {
    super.onInit();

    Future.delayed(const Duration(milliseconds: 300), () {
      Loading.showLoading(null);
      // 获取服务器上的固件列表
      _fetchFirmwareList();
    });
  }

  // 获取服务器上的固件列表
  Future<void> _fetchFirmwareList() async {
    final VehicleModel vehicleModel =
        GlobalService.to.currentVehicleModel.value;
    // 从服务器获取固件列表
    ApiHelper()
        .checkFirmwareUpgrade(vehicleModel.sn, vehicleModel.productModel,
            vehicleModel.firmwareInfoList)
        .then((response) {
      // 将所有 model 的 versions 扁平化为一个 List<String>
      final List<FirmwareUpgradeSubModel> models = [];
      for (final model in response.firmwareUpgradeModels) {
        for (final item in model.versions) {
          models.add(item);
        }
      }
      // 将models通过deviceId与cacheList进行匹配，更新latestVersion、file字段赋值给cacheList对应的model
      for (final cacheModel in vehicleModel.firmwareInfoList) {
        for (final upgradeModel in models) {
          if (cacheModel.deviceId == upgradeModel.deviceId) {
            cacheModel.latestVersion.value = upgradeModel.latestVersion;
            cacheModel.updateDescription.value = response.summary;
            int result = Utils.compareVersions(
                cacheModel.latestVersion.value, cacheModel.appVersion);
            switch (result) {
              case 1:
                cacheModel.status.value = UpgradeStatus.updateAvailable;
                break;
              case -1:
                cacheModel.status.value = UpgradeStatus.downgradeAvailable;
                break;
              default:
                cacheModel.status.value = UpgradeStatus.upToDate;
            }
            cacheModel.file = upgradeModel.file;
            break;
          }
        }
      }
      state.currentUpdatingModels.value = vehicleModel.firmwareInfoList;
      Loading.dismiss();
    }).catchErrorHandler();
  }

  // 升级单个固件
  Future<bool> updateFirmware(FirmwareInfoModel device) async {
    final Completer<bool> completer = Completer<bool>();
    // 判断是否已经有其他固件在升级中
    bool isAnyUpdating = state.currentUpdatingModels
        .any((model) => model.status.value == UpgradeStatus.updating);
    if (isAnyUpdating) {
      Loading.showToast(local.please_wait_for_other_updates_to_complete);
      if (!completer.isCompleted) {
        completer.complete(false);
      }
      return completer.future;
    }
    device.status.value = UpgradeStatus.updating;
    device.progress.value = 0;
    if (device.deviceType == null) {
      Loading.showError(local.unknown_device);
      if (!completer.isCompleted) {
        completer.complete(false);
      }
      return completer.future;
    }

    // 获取当前蓝牙MTU大小，packetSize不是最终大小，协议里需要根据MTU大小进行分包传输，需要去除帧头/尾/转义字符等开销
    int mtu = await VechileConnectionService.to.mtu ?? 100;

    // 成功处理函数
    successHandler() {
      GlobalService.to.isUpgrading = false;
      if (!completer.isCompleted) {
        completer.complete(true);
      }
    }

    // 错误处理函数
    failedHandler() {
      GlobalService.to.isUpgrading = false;
      device.status.value = UpgradeStatus.updateFailed;
      device.progressDescription.value = local.update_failed;
      device.progress.value = 0;
      if (!completer.isCompleted) {
        completer.complete(false);
      }
    }

    // 下载固件在整个升级进程中配比为5%，传输固件占比为99%
    // 固件升级过程
    protocolMixinStartOTA(
      device.file,
      device.latestVersion.value,
      device.deviceType!,
      onStatus: (p0) {
        debugPrint("✅ 升级状态: $p0");
        device.progressDescription.value = p0.msg;
        switch (p0) {
          case OtaUpgradeStatus.transferSuccess:
            device.progress.value = 100;
            break;
          case OtaUpgradeStatus.upgradeSuccess:
            // 升级成功
            successHandler();
            device.status.value = UpgradeStatus.upToDate;
            device.progressDescription.value = local.update_successful;
            break;
          case OtaUpgradeStatus.downloadFailed:
          case OtaUpgradeStatus.busy:
          case OtaUpgradeStatus.readFileFailed:
          case OtaUpgradeStatus.writeFileFailed:
          case OtaUpgradeStatus.transferFailed:
          case OtaUpgradeStatus.upgradeFailed:
            failedHandler();
            break;
          default:
            // 其他状态不处理
            break;
        }
      },
      onDownloadProgress: (p0) {
        GlobalService.to.isUpgrading = true;
        debugPrint("✅ 下载进度: $p0");
        device.progress.value = (p0 * 0.05).toInt();
      },
      onTransferProgress: (p0) {
        GlobalService.to.isUpgrading = true;
        debugPrint("✅ 传输进度: $p0");
        device.progress.value = (5 + p0 * 95).toInt();
      },
      onUserActionRequired: (p0, complete) {
        debugPrint("✅ 用户操作类型: $p0");
        switch (p0) {
          case UserActionType.none:
            // 无需用户操作，直接完成回调
            complete(true);
            break;
          default:
            break;
        }
      },
      onTotalSize: (p0) {
        debugPrint("✅ 总大小: $p0");
      },
      maxMtu: mtu,
    ).catchErrorHandler(
      onError: (p0) {
        failedHandler();
      },
    );
    return completer.future;
  }

  // 一键升级所有固件
  void updateAllFirmware() async {
    state.isUpdatingAll.value = true;
    for (final device in state.currentUpdatingModels) {
      if (device.status.value == UpgradeStatus.updateAvailable ||
          device.status.value == UpgradeStatus.downgradeAvailable) {
        bool result = await updateFirmware(device);
        if (!result) {
          // 某个固件升级失败，停止一键升级
          break;
        }
      }
    }
    state.isUpdatingAll.value = false;
  }
}
